//
//  TimeAdjustmentViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/23/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "TimeAdjustmentViewController.h"

@interface TimeAdjustmentViewController ()

@end

@implementation TimeAdjustmentViewController
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize index=_index;

@synthesize warningSection=_warningSection;
@synthesize cellPhoneTimeSection=_cellPhoneTimeSection;
@synthesize controllerTimeSection=_controllerTimeSection;
@synthesize masterCycleTimeSection=_masterCycleTimeSection;

@synthesize addOffsetButton=_addOffsetButton;
@synthesize minusOffsetButton=_minusOffsetButton;
@synthesize sections=_sections;
@synthesize timer=_timer;
@synthesize masterTimerLabel=_masterTimerLabel;
@synthesize cellPhoneTimeLabel=_cellPhoneTimeLabel;
@synthesize offsetTimerLabel=_offsetTimerLabel;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    
    [_warningSection release];
    [_cellPhoneTimeSection release];
    [_controllerTimeSection release];
    [_masterCycleTimeSection release];
    [_addOffsetButton release];
    [_minusOffsetButton release];
    [_timer release];
    [_cellPhoneTimeLabel release];
    [_masterTimerLabel release];
    [_offsetTimerLabel release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    //    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
    //    [self.navigationController.view addSubview:backgroundView];
    //    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if (!_warningSection) {
        _warningSection=[[TableSection alloc]init];
        
        _warningSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_warningSection.contents addObject:@"The time adjustment here changes the base time of the whole agency!"];
        
        _warningSection.header=@"Warning";
    }
    
    if (!_cellPhoneTimeSection) {
        _cellPhoneTimeSection=[[TableSection alloc]init];
        
        _cellPhoneTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        
        NSDate *currentDateTime = [NSDate date]; 
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
        NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
        NSLog(@"%@", dateInStringFormated);
        
//        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.timingPattern.cycleLength intValue] offSet:0 syncTime:self.agency.syncTime standardTimeOff:0];
        [_cellPhoneTimeSection.contents addObject:dateInStringFormated];
        
//        [_cellPhoneTimeSection.contents addObject:dateInStringFormated];
        
        _cellPhoneTimeSection.header=@"Cell Phone Time";
    }
    
    if (!_controllerTimeSection) {
        _controllerTimeSection=[[TableSection alloc]init];
        
        _controllerTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
//        int baseTimeOffset=[self.agency.baseTimeOffset intValue];
        NSDate *currentDateTime = [NSDate date]; 
        NSDate *agencyTime=[currentDateTime dateByAddingTimeInterval:[self.agency.baseTimeOffset intValue]];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
        NSString *dateInStringFormated = [dateFormatter stringFromDate:agencyTime];
        NSLog(@"%@", dateInStringFormated);
        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.timingPattern.cycleLength intValue] time:agencyTime offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        [_controllerTimeSection.contents addObject:[NSString stringWithFormat:@"%@  %d/%@",dateInStringFormated,cycleTimer,self.timingPattern.cycleLength]];
        
        _controllerTimeSection.header=@"Master Timer";
    }
    if (!_masterCycleTimeSection) {
        _masterCycleTimeSection=[[TableSection alloc]init];
        
        _masterCycleTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_masterCycleTimeSection.contents addObject:self.agency.baseTimeOffset];
        
        _masterCycleTimeSection.header=@"Base Time Offset";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        //        [_sections addObject:self.agencyNameSection];
        [_sections addObject:self.warningSection];
        [_sections addObject:self.cellPhoneTimeSection];
        [_sections addObject:self.controllerTimeSection];
        [_sections addObject:self.masterCycleTimeSection];
    }
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,nil ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.agency=nil;
    self.subSystem=nil;
    self.timingPattern=nil;
    
    self.warningSection=nil;
    self.cellPhoneTimeSection=nil;
    self.controllerTimeSection=nil;
    self.masterCycleTimeSection=nil;
    self.addOffsetButton=nil;
    self.minusOffsetButton=nil;
    self.sections=nil;
    self.timer=nil;
    self.cellPhoneTimeLabel=nil;
    self.masterTimerLabel=nil;
    self.offsetTimerLabel=nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
//    [self updateViewController];
    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)viewWillDisappear:(BOOL)animated
{
//    self.timingPattern.timingPatternName=self.timingPatternNameTextView.text;
//    self.timingPattern.cycleLength=self.timingPatternCycleTextView.text;
//    [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [self.timer invalidate];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;  
     cell.selectionStyle=UITableViewCellSelectionStyleNone;
    switch (indexPath.section) {
        case 0:
        {
            [cell setBackgroundColor:[UIColor redColor]];
            cell.textLabel.text=sectionContentString;
//            cell.textLabel.backgroundColor=[UIColor redColor];
        }
            break;
        case 1:
        {
            [cell setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
            cell.textLabel.text=sectionContentString;
            self.cellPhoneTimeLabel=cell.textLabel;
        }
            break;
        case 2:
        {
            [cell setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
            cell.textLabel.text=sectionContentString;
            self.masterTimerLabel=cell.textLabel;
        }
            break;
        case 3:
        {
            [cell setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
            cell.textLabel.text=sectionContentString;
            cell.textLabel.textAlignment = UITextAlignmentCenter;
            
            {
                UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                [newbutton setFrame:CGRectMake(10,1,90,43)];
                [newbutton setTitle:@"-" forState:UIControlStateNormal];
                newbutton.titleLabel.textAlignment=UITextAlignmentCenter;
                //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
                //            [newbutton setTag:(section)];
                [newbutton addTarget:self action:@selector(minusBaseTimeOffset) 
                    forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:newbutton];
            }
            
            {
                UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                [newbutton setFrame:CGRectMake(220,1,90,43)];
                [newbutton setTitle:@"+" forState:UIControlStateNormal];
                newbutton.titleLabel.textAlignment=UITextAlignmentCenter;
                //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
                //            [newbutton setTag:(section)];
                [newbutton addTarget:self action:@selector(addBaseTimeOffset) 
                    forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:newbutton];
            }
            
        }
            break;
            
        default:
            break;
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = UITextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkGrayColor];
    
    
    [headerView addSubview:aLabel];
    
    switch (section) {
        case 0:case 1:case 2:
            return headerView;
            break;
        case 3:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            [newbutton setFrame:CGRectMake(220,4,90,30)];
            [newbutton setTitle:@"Set to 0" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            //            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickSetOffsetToZero:)
                              forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
            
            return headerView;
        }
            break;
            
        default:
            break;
    }
    
    
    
    return headerView;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}
#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

#pragma mark - Customized Functions
- (id) initWithNibNameAndAgency:(NSString *)nibName timingPattern:(TimingPattern *)timingPattern subSystem:(SubSystem *)subSystem agency:(Agency *)agency index:(int)index bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.agency=agency;
    self.subSystem=subSystem;
    self.timingPattern=timingPattern;
    self.index=index;
    return self;
}

- (void) updateTimer:(id) sender {
    int cycle=[self.timingPattern.cycleLength intValue];
    if (cycle>10) {
        {
            
            NSDate *currentDateTime = [NSDate date]; 
            NSDate *agencyTime=[currentDateTime dateByAddingTimeInterval:[self.agency.baseTimeOffset intValue]];
            int cycleTimer=[TrafficSignalTimer calculateCycleTimer:cycle time:agencyTime offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
            [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
            NSString *dateInStringFormated = [dateFormatter stringFromDate:agencyTime];
            
            self.masterTimerLabel.text=[NSString stringWithFormat:@"%@  %d/%@",dateInStringFormated,cycleTimer,self.timingPattern.cycleLength];
        }
        
        
        
        {
            NSDate *currentDateTime = [NSDate date]; 
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
            [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
            NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
            self.cellPhoneTimeLabel.text=dateInStringFormated;
        }
    }
    
}

- (void) addBaseTimeOffset
{
    int baseTimeOffset=[self.agency.baseTimeOffset intValue];
    baseTimeOffset=baseTimeOffset+1;
    self.agency.baseTimeOffset=[NSString stringWithFormat:@"%d", baseTimeOffset];
    [XMLParser updateAgency:self.agency];
    
    [self updateViewController];
    
}
- (void) minusBaseTimeOffset
{
    int baseTimeOffset=[self.agency.baseTimeOffset intValue];
    baseTimeOffset=baseTimeOffset-1;
    self.agency.baseTimeOffset=[NSString stringWithFormat:@"%d", baseTimeOffset];
    [XMLParser updateAgency:self.agency];
    
    [self updateViewController];
}
- (void) updateViewController
{
    if (self.warningSection) {
        self.warningSection=[[[TableSection alloc]init] autorelease];
        
        self.warningSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.warningSection.contents addObject:@"The time adjustment here changes the base time of the whole agency!"];
        
        self.warningSection.header=@"Warning";
    }
    
    if (self.cellPhoneTimeSection) {
        self.cellPhoneTimeSection=[[[TableSection alloc]init] autorelease];
        
        self.cellPhoneTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        
        NSDate *currentDateTime = [NSDate date]; 
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
        NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
        NSLog(@"%@", dateInStringFormated);
        
        //        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.timingPattern.cycleLength intValue] offSet:0 syncTime:self.agency.syncTime standardTimeOff:0];
        [self.cellPhoneTimeSection.contents addObject:dateInStringFormated];
        
        //        [_cellPhoneTimeSection.contents addObject:dateInStringFormated];
        
        self.cellPhoneTimeSection.header=@"Cell Phone Time";
    }
    
    if (self.controllerTimeSection) {
        self.controllerTimeSection=[[[TableSection alloc]init] autorelease];
        
        self.controllerTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        //        int baseTimeOffset=[self.agency.baseTimeOffset intValue];
        NSDate *currentDateTime = [NSDate date]; 
        NSDate *agencyTime=[currentDateTime dateByAddingTimeInterval:[self.agency.baseTimeOffset intValue]];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
        NSString *dateInStringFormated = [dateFormatter stringFromDate:agencyTime];
        NSLog(@"%@", dateInStringFormated);
        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.timingPattern.cycleLength intValue] time:agencyTime offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        [self.controllerTimeSection.contents addObject:[NSString stringWithFormat:@"%@  %d/%@",dateInStringFormated,cycleTimer,self.timingPattern.cycleLength]];
        
        self.controllerTimeSection.header=@"Master Timer";
    }
    if (self.masterCycleTimeSection) {
        self.masterCycleTimeSection=[[[TableSection alloc]init] autorelease];
        
        self.masterCycleTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.masterCycleTimeSection.contents addObject:self.agency.baseTimeOffset];
        
        self.masterCycleTimeSection.header=@"Base Time Offset";
    }
    if (self.sections) {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        //        [_sections addObject:self.agencyNameSection];
        [self.sections addObject:self.warningSection];
        [self.sections addObject:self.cellPhoneTimeSection];
        [self.sections addObject:self.controllerTimeSection];
        [self.sections addObject:self.masterCycleTimeSection];
    }
    [self.tableView reloadData];

}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void) clickSetOffsetToZero:(id)sender
{
    self.agency.baseTimeOffset=[NSString stringWithFormat:@"%d", 0];
    [XMLParser updateAgency:self.agency];
    
    [self updateViewController];
}
@end
